package com.mryan.esjd.service;

import com.alibaba.fastjson.JSON;
import com.mryan.esjd.pojo.ParseJD;
import com.mryan.esjd.utils.HtmlParseUtil;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description：TODO
 * @Author MRyan
 * @Date 2020/6/23 21:32
 * @Version 1.0
 */
@Service
public class ParseJDservice {


    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;


    /**
     * 爬虫爬取数据 并且存入elasticSearch数据库中
     *
     * @param keywords
     * @return
     * @throws IOException
     */
    public Boolean parseJD(String keywords) throws IOException {
        List<ParseJD> parseJD = new HtmlParseUtil().getParseJD(keywords);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < parseJD.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_parse").source(JSON.toJSONString(parseJD.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }


    /**
     * 获取数据 达到搜索功能
     *
     * @param keyword
     * @param page
     * @param pagesize
     * @return
     */
    public List<Map<String, Object>> srarchPage(String keyword, int page, int pagesize) throws IOException {
        if (page <= 1) {
            page = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_parse");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from(page);
        searchSourceBuilder.size(pagesize);

        //模糊匹配
        MatchQueryBuilder title = QueryBuilders.matchQuery("title", keyword);
        //开启模糊
        title.fuzziness(Fuzziness.AUTO);
        searchSourceBuilder.query(title);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        //多个高亮显示
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String, Object>> lists = new ArrayList<>();
        for (SearchHit documentFields : search.getHits().getHits()) {

            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField title1 = highlightFields.get("title");
            //原来的结果
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();

            //解析高亮字段 将原来的字段换为高亮的字段

            if (title1 != null) {
                Text[] fragments = title1.fragments();
                StringBuilder n_title = new StringBuilder();
                for (Text text : fragments) {
                    n_title.append(text);
                }
                sourceAsMap.put("title", n_title);
            }
            lists.add(sourceAsMap);
        }
        return lists;
    }


}
